package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;

    @Override
    public Cart save(Cart cart) {
        //判断当前cart在表中是否存在
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(cart.getSetmealId() != null, Cart::getSetmealId, cart.getSetmealId())
                .eq(cart.getDishId() != null, Cart::getDishId, cart.getDishId())
                .eq(Cart::getUserId, UserHolder.get().getId());

        Cart cartFromDB = cartMapper.selectOne(wrapper);


        if (cartFromDB != null) {
            //如果数据库里有,则只需将number+1
            cartFromDB.setNumber(cartFromDB.getNumber() + 1);
            cartMapper.updateById(cartFromDB);
            return cartFromDB;
        } else {
            //如果数据库里没有当前用户所选菜或套餐,便将此cart保存
            cart.setUserId(UserHolder.get().getId());
            cart.setNumber(1);
            cart.setCreateTime(new Date());
            cartMapper.insert(cart);
            return cart;
        }
    }

    @Override
    public List<Cart> findList() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        return cartMapper.selectList(wrapper);
    }

    @Override
    public void clean() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        cartMapper.delete(wrapper);
    }

    @Override
    public Cart sub(Long dishId, Long setmealId) {
        /*UpdateWrapper<Cart> wrapper = new UpdateWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());*/
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId())
                .eq(dishId != null, Cart::getDishId, dishId)
                .eq(setmealId != null, Cart::getSetmealId, setmealId);
        Cart cart = cartMapper.selectOne(wrapper);
        if (cart != null) {
            cart.setNumber(cart.getNumber() - 1);
            if (cart.getNumber() <= 0) {
                cartMapper.deleteById(cart.getId());

            } else {
                cartMapper.updateById(cart);
            }
        }
        return cart;
    }
}
